package work.xiaohong.mina.test1;

import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * @author Kevin
 * @data 4/25/2022 11:13 AM
 * @description
 **/
public class MinaServer {

  public static void main(String[] args) {
    IoAcceptor acceptor = new NioSocketAcceptor();

    // 设置编码过滤器
    acceptor.getFilterChain().addLast("codec",new ProtocolCodecFilter(
            new TextLineCodecFactory(
                    // 字符集
                    Charset.forName("UTF-8"),
                    // 设置编码器 根据windows里的换行符进行分隔
                    LineDelimiter.WINDOWS.getValue(),
                    // 设置解码器
                    LineDelimiter.WINDOWS.getValue()
            )
    ));

    // 设置读缓冲区大小
    acceptor.getSessionConfig().setReadBufferSize(1024);
    // 设置读和写加入空闲状态的时间 单位是s
    acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);

    acceptor.setHandler(new MyHandler());

    // 绑定端口号
    try {
      acceptor.bind(new InetSocketAddress(8080));
      System.out.println("端口为8080的服务端启动成功");
    }
    catch (IOException e) {
      System.out.println("端口为8080的服务端启动失败");
      e.printStackTrace();
    }


  }

}
